package com.example.base.base.activity

import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * @Description
 * @department 城市元宇宙组
 * @Author niushilong
 * @Date 2024-04-07 11:16
 */
abstract class BaseVBActivity<VM: ViewModel, VB: ViewBinding> : BaseActivity(){

    protected lateinit var mViewModel: VM

    private var _binding: VB? = null
    protected val mBinding: VB
        get() = requireNotNull(_binding) { "ViewBinding对象为空" }

    // 反射创建ViewModel
    protected open fun createViewModel(): VM{
        val clazz =
            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
        return ViewModelProvider(this)[clazz]
    }

    // 反射创建ViewBinding
    protected open fun createViewBinding(){
        val clazz: Class<*> = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1] as Class<VB>

        try {
            _binding = clazz.getMethod("inflate", LayoutInflater::class.java).invoke(null, layoutInflater) as VB
        } catch (e: Exception){
            e.printStackTrace()
            throw java.lang.IllegalArgumentException("无法通过反射创建ViewBinding对象")
        }

    }

    override fun setContentView() {
        setContentView(mBinding.root)
        mViewModel = createViewModel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        createViewBinding()
        super.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}